package com.xhq.test.springboot.springbootdemo.feign;

import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @author huiny
 * @since 2021/4/10 11:52
 */
@Configuration
public class FeignConfig  {

    @Bean
    public RequestInterceptor getRequestInterceptor() {
        return new MyRequestInterceptor();
    }

    @Bean
    public Request.Options getOptions() {
        return new Request.Options(1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS, true);
    }

    public static class MyRequestInterceptor implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            requestTemplate.header("x-time", LocalDateTime.now().toString());
        }
    }

    public static class MyEncoder extends SpringEncoder {

        public MyEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
            super(messageConverters);
        }

        public MyEncoder(SpringFormEncoder springFormEncoder, ObjectFactory<HttpMessageConverters> messageConverters) {
            super(springFormEncoder, messageConverters);
        }

        @Override
        public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException {
            super.encode(requestBody, bodyType, request);
        }
    }

}
